#include <sys/sem.h>  
#include <fcntl.h>  
#include <unistd.h>  
#include <errno.h>  
#include <sys/types.h>  
#include <sys/ipc.h>  
#include <sys/shm.h>  
#include <stdio.h>  

union semun{  
	int val;  
	struct semid_ds *buf;  
	unsigned short int *array;  
};  

main(int argc,char **argv)  
{  
	int i,shm_id,sem_id,oflag;  
	int value;  
	char *ptr;  
	struct sembuf lock_it;  
	union semun options;  
	oflag=0644|IPC_CREAT;  
	
	if(argc!=2)  
	{  
		printf("usage:server <pathname>\n");  
		exit(1);  
	}  

	if((sem_id=semget(ftok(argv[1],0),100,oflag))<0)  
		perror("semget");  

	options.val=1;  
	semctl(sem_id,0,SETVAL,options);  

	if((shm_id=shmget(ftok(argv[1],0),4096,oflag))<0) 
		perror("shmget");  
	printf("key_t:%d\n",ftok(argv[1],0));  
	printf("shm_id:%d\n",shm_id);  

	if((ptr=shmat(shm_id,NULL,0))<0) 
		perror("shmat");  

	while(1)  
	{  
		if((strcmp(ptr,"\0"))==0)  
		{  
			continue;  
		}  
		else  
		{  
			if((strcmp(ptr,"q\n"))==0) 
				break;  
			
			lock_it.sem_num=0;  
			lock_it.sem_op=-1;  
			lock_it.sem_flg=IPC_NOWAIT;  
			
			semop(sem_id,&lock_it,1);
			printf("server:%s",ptr);  
			
			strcpy(ptr,"\0");  
			lock_it.sem_num=0;  
			lock_it.sem_op=1;  
			lock_it.sem_flg=IPC_NOWAIT;  
			
			semop(sem_id,&lock_it,1);
		}  
	}  
	
	shmdt(ptr);

	semctl(sem_id,IPC_RMID,0);  
	shmctl(shm_id,IPC_RMID,0);  
	
	exit(0);  
}  
